﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using AutoMapper;
using Auth.Application.Dtos;
using Auth.Domain.TableEntity;
using Auth.Repository.IRepositories;
using Auth.Utility;
using SqlSugar;
using Microsoft.AspNetCore.Http;
using System.Linq;

namespace Auth.Application
{
    public class DepartmentAppService : IDepartmentAppService
    {
        private readonly IDepartmentRepository _repository;
        private readonly IUserRepository _userRepository;
        private readonly IHttpContextAccessor _httpContext;

        public DepartmentAppService(IDepartmentRepository repository,IUserRepository userRepository, IHttpContextAccessor httpContext)
        {
            _repository = repository;
            _userRepository = userRepository;
            _httpContext = httpContext;
        }

        public int Delete(List<string> ids)
        {
            return _repository.DeleteWithCache(ids);
        }

        /// <summary>
        /// 根据主键删除部门
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public int Delete(string id)
        {
            var depart = _repository.QuerySingle(id);
            var departmentIds = _repository.QueryByWhereWithCache(s=>SqlFunc.StartsWith(s.No,depart.No),s=>s.Id).Select(s=>s.Id);
            var Exist = _userRepository.Any(a=>departmentIds.Contains(a.DepartmentId));
            if (Exist)
                throw new MessageBox("该部门下下存在用户，暂不能删除。");
            return _repository.DeleteWithCache(departmentIds.ToList());
        }
        public int Insert(DepartmentDto entity)
        {
            var exist = _repository.Any(s => s.Name == entity.Name || s.Code == entity.Code);
            if (exist)
                throw new MessageBox("部门名称或编号重复！");
            return _repository.InsertWithCache(Mapper.Map<departments>(entity));
        }

        public int InsertRange(List<DepartmentDto> entities)
        {
            return _repository.InsertRangeWithCache(Mapper.Map<List<departments>>(entities));
        }

        public int Update(DepartmentDto entity)
        {
            var d = _repository.QueryByWhereWithCache(s => s.Name == entity.Name || s.Code == entity.Code, s => s.Id).First();
            if (d != null && d.Id != entity.Id)
                throw new MessageBox("部门名称或编号重复！");
            return _repository.UpdateWithCache(Mapper.Map<departments>(entity));
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        public List<DepartmentDto> GetAllList()
        {
            Expression<Func<departments, object>> orderExpression = s => SqlFunc.ToDecimal(s.No);

            return Mapper.Map<List<DepartmentDto>>(_repository.QueryByWhereWithCache(it => !SqlFunc.IsNullOrEmpty(it.Id),
                orderExpression, OrderByType.Desc));
        }

        /// <summary>
        /// 新增或修改
        /// </summary>
        /// <param name="dto">实体</param>
        /// <returns></returns>
        public bool InsertOrUpdate(DepartmentDto dto)
        {
            if (string.IsNullOrEmpty(dto.Id))
            {
                dto.Id = Guid.NewGuid().ToString();
                dto.CreateTime = DateTime.Now;
                dto.CreateUserId = _httpContext.HttpContext.Session.GetString("CurrentUserId");
                return Insert(dto) > 0;
            }

            return Update(dto) > 0;
        }

        public LayuiTableModel<DepartmentDto> GetTableList(int page, int size, List<IConditionalModel> searchParam,
            string orderField="")
        {
            LayuiTableModel<DepartmentDto> tableModel = new LayuiTableModel<DepartmentDto>
            {
                Success = true,
                Code = 0,
                Count = _repository.QueryCount(searchParam),
                Data = Mapper.Map<List<DepartmentDto>>(_repository.QueryByWherePage(page, size, searchParam, orderField))
            };
            return tableModel;
        }

        public DepartmentDto QuerySingle(string id)
        {
            var entity = _repository.QuerySingle(id);
            return Mapper.Map<DepartmentDto>(entity);
        }

        /// <summary>
        /// 查询全部
        /// </summary>
        /// <returns></returns>
        public List<DepartmentDto> QueryAll(Expression<Func<departments, bool>> whereExpression)
        {
            return Mapper.Map<List<DepartmentDto>>(_repository.QueryByWhereWithCache(whereExpression, null));
        }

        /// <summary>
        /// 生成下级部门编号
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetNextNo(string id)
        {
            var parentDepart = QuerySingle(id);
            Expression<Func<departments, bool>> filter = s => s.ParentId == id;
            //根据编号的降排序
            var childDepartList = _repository.QueryByWhereWithCache(filter, s => SqlFunc.ToDecimal(s.No), OrderByType.Desc);
            //当前没有下级则返回当前编号*100+1 ，例：当前编号为1，则返回101
            if (childDepartList.Count < 1)
            {
                return parentDepart != null ? (decimal.Parse(parentDepart.No) * 100 + 1).ToString("#") : "";
            }

            //如果已经包含下级菜单，返回下级菜单最大编号+1
            return (decimal.Parse(childDepartList[0].No) + 1).ToString("#");
        }

        /// <summary>
        /// 获取同级No
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetNo(string id)
        {
            var depart = QuerySingle(id);
            Expression<Func<departments, bool>> filter = s => s.ParentId == depart.ParentId;
            //根据编号的降排序
            var childList = _repository.QueryByWhereWithCache(filter, s => SqlFunc.ToDecimal(s.No), OrderByType.Desc);

            //最大编号+1
            return (decimal.Parse(childList[0].No) + 1).ToString("#");
        }
    }
}